package my.wudm.yummy.worker;

import cn.zyzpp.AiPa;
import cn.zyzpp.executor.AiPaExecutor;
import cn.zyzpp.util.AiPaUtil;
import cn.zyzpp.worker.AiPaWorker;
import my.wudm.yummy.common.BaseParse;
import my.wudm.yummy.common.constant.Const;
import my.wudm.yummy.common.factory.ParseFactory;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class WebWorker implements AiPaWorker {
    private volatile boolean isParseCatalog = true;
    public WebWorker(boolean isParseCatalog){
        this.isParseCatalog = isParseCatalog;
    }
    @Override
    public Object run(Document document, AiPaUtil aiPaUtil) {
        BaseParse parse = ParseFactory.getInstance(Const.PARSE_TYPE_BIQU);
        return isParseCatalog ? parse.parseCatalog(document, aiPaUtil) : parse.parseContent(document, aiPaUtil);
    }

    @Override
    public Object fail(String s) {
        return null;
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ExecutionException, InterruptedException {
        //准备网址集合
        List<String> linkList = new ArrayList<>();
        linkList.add("http://www.biquyun.com/18_18698/");
//        linkList.add("http://www.biquyun.com/12_12058/");
        //第一步：新建AiPa实例
        boolean isParseCatalog = true;
        AiPaExecutor aiPaExecutor = AiPa.newInstance(new WebWorker(isParseCatalog)).setCharset(Charset.forName("GBK"));
        //第二步：提交任务
//        for (int i = 0; i < 10; i++) {
            aiPaExecutor.submit(linkList);
//        }
        //第三步：读取返回值
        List<Future> futureList = aiPaExecutor.getFutureList();
        for (int i = 0; i < futureList.size(); i++) {
            //get() 方法会阻塞当前线程直到获取返回值
            Object x = futureList.get(i).get();
            System.out.println(x);
        }
        //第四步：关闭线程池
        aiPaExecutor.shutdown();
    }
}
